package com.zhucai.credit.monitor.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.zhucai.credit.monitor.bean.SendMsgResult;
import com.zhucai.credit.monitor.service.INotificationService;

@Service("EMAIL")
public class EmailNotificationServiceImpl implements INotificationService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Value("${notification.mail.sendto}")
	private String to;

	@Value("${spring.mail.username}")
	private String from;
	
	@Value("${spring.mail.sendname}")
	private String sendName;
	
	//发送邮件开关
	@Value("${notification.mail.issend}")
	private String sendtatus;
	
	@Autowired
	private  JavaMailSender mailSender;
	
	@Autowired
	private TemplateEngine templateEngine;

	
	/**
	 * 金融自定义异常发送邮件
	 * @version 2018年8月15日
	 * @param ca
	 * @return
	 */
	@Override
	public SendMsgResult notification(String err) {
		if(!"true".equalsIgnoreCase(sendtatus)){
			return null;
		}
		logger.info("### 金融自定义异常发送邮件start");
		try {
			System.setProperty("mail.mime.splitlongparameters", "false");
			MimeMessage message = mailSender.createMimeMessage();
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
			//动态设置邮件标题
			String subject = "金融自定义异常"+sf.format(new Date());
			//动态设置发送邮件名称
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");  
			messageHelper.setFrom(sendName+"<"+from+">");  
			messageHelper.setSubject(subject);  
			messageHelper.setTo(to.split(","));
			Context context = new Context();
			context.setVariable("err", err);
			context.setVariable("host", getHostName());
			
			String x = templateEngine.process("error/error", context);
			messageHelper.setText(x,true);
			mailSender.send(message);
		} catch (MessagingException e) {
			e.getCause();
		}
		

		logger.info("### 金融自定义异常发送邮件success");
		return null;
	}
	private String getHostName() {
        try {
			InetAddress addr = InetAddress.getLocalHost();  
			String hostName=addr.getHostName().toString();
			return hostName;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        return "";
	}
}
